package com.bs.visitservice.controller.seller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bs.visitservice.entity.Product;
import com.bs.visitservice.entity.ProductType;
import com.bs.visitservice.service.ProductService;
import com.bs.visitservice.service.ProductTypeService;
import com.bs.visitservice.utils.ParamUtils;
import com.bs.visitservice.utils.Result;
import com.bs.visitservice.utils.ResultUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * 产品信息管理
 */
@RestController
@RequestMapping("/seller")
public class ProductController {

    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private ProductService productService;



    /**
     * 查询店铺产品类型
     * @param cond
     * @return
     */
    @RequestMapping(value = "/queryProductType",method = RequestMethod.POST)
    public Result queryProductType(@RequestBody Map cond){
        ProductType pt = (ProductType)ResultUtil.transObject(cond, ProductType.class);
        IPage page = ParamUtils.getPage(cond);
        LambdaQueryWrapper<ProductType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductType::getSellerNo,pt.getSellerNo());
        page = productTypeService.pageMaps(page,wrapper);
        List<Map<String, Object>> maps = page.getRecords();
        Map<String,Object> result = new HashMap<>();
        result.put("total",page.getTotal());
        result.put("datas",maps);
        return  Result.success(result);
    }
    /**
     * 添加店铺产品类型
     * @param cond
     * @return
     */
    @RequestMapping(value = "/saveProductType",method = RequestMethod.POST)
    public Result saveProductType(@RequestBody Map cond){
        ProductType pt = (ProductType)ResultUtil.transObject(cond, ProductType.class);
        boolean isSuc = productTypeService.save(pt);
        if(isSuc){
            return  Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 删除店铺产品类型
     * @param cond
     * @return
     */
    @Transactional
    @RequestMapping(value = "/removeProductType",method = RequestMethod.POST)
    public Result removeProductType(@RequestBody Map cond){
        ProductType pt = (ProductType)ResultUtil.transObject(cond, ProductType.class);
        productTypeService.removeById(pt);
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getProductType,pt.getNo());
        //删除产品类型下的产品
        productService.remove(wrapper);
        return Result.success(null);
    }
    /**
     * 更新店铺产品类型
     * @param cond
     * @return
     */
    @RequestMapping(value = "/updateProductType",method = RequestMethod.POST)
    public Result updateProductType(@RequestBody Map cond){
        ProductType pt = (ProductType)ResultUtil.transObject(cond, ProductType.class);
        boolean isSuc = productTypeService.updateById(pt);
        if(isSuc){
            return  Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 更新店铺产品
     * @return
     */
    @RequestMapping(value = "/updateProduct",method = RequestMethod.POST)
    public Result updateProduct(HttpServletRequest request){
        boolean isSuc = false;
        InputStream is = null;
        try {
            request.setCharacterEncoding("utf-8"); //设置编码
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
            Map<String, String[]> parameterMap = req.getParameterMap();
            Map<String,Object> transMap = new HashMap<>();
            parameterMap.forEach((k,v)->{
                transMap.put(k,v[0]);
            });
            Product product = (Product)ResultUtil.transObject(transMap, Product.class);
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                is = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = is.read(bytes))>0){
                    bos.write(bytes, 0,len);
                }
                byte[] res = bos.toByteArray();
                product.setPhoto(res);
            }
            isSuc = productService.updateById(product);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 添加店铺产品
     * @return
     */
    @RequestMapping(value = "/saveProduct",method = RequestMethod.POST)
    public Result saveProduct(HttpServletRequest request){
        boolean isSuc = false;
        InputStream is = null;
        try {
            request.setCharacterEncoding("utf-8"); //设置编码
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
            Map<String, String[]> parameterMap = req.getParameterMap();
            Map<String,Object> transMap = new HashMap<>();
            parameterMap.forEach((k,v)->{
                transMap.put(k,v[0]);
            });
            Product product = (Product)ResultUtil.transObject(transMap, Product.class);
            product.setStatus(1);
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                is = file.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] bytes = new byte[2048];
                int len = 0;
                while ((len = is.read(bytes))>0){
                    bos.write(bytes, 0,len);
                }
                byte[] res = bos.toByteArray();
                product.setPhoto(res);
            }
            isSuc = productService.save(product);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if(isSuc){
            return Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 删除店铺产品
     * @param cond
     * @return
     */
    @RequestMapping(value = "/removeProduct",method = RequestMethod.POST)
    public Result removeProduct(@RequestBody Map cond){
        Product pt = (Product)ResultUtil.transObject(cond, Product.class);
        boolean isSuc = productService.removeById(pt);
        if(isSuc){
            return  Result.success(null);
        }
        return Result.error(null);
    }

    /**
     * 上架
     * @param cond
     * @return
     */
    @RequestMapping(value = "/showProduct",method = RequestMethod.POST)
    public Result showProduct(@RequestBody Map cond){
        Product pt = (Product)ResultUtil.transObject(cond, Product.class);
        pt.setStatus(0);
        boolean isSuc = productService.updateById(pt);
        if(isSuc){
            return  Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 下架
     * @param cond
     * @return
     */
    @RequestMapping(value = "/hideProduct",method = RequestMethod.POST)
    public Result hideProduct(@RequestBody Map cond){
        Product pt = (Product)ResultUtil.transObject(cond, Product.class);
        pt.setStatus(1);
        boolean isSuc = productService.updateById(pt);
        if(isSuc){
            return  Result.success(null);
        }
        return Result.error(null);
    }
    /**
     * 按照条件查询店铺产品
     * @param cond
     * @return
     */
    @RequestMapping(value = "/queryProduct",method = RequestMethod.POST)
    public Result queryProduct(@RequestBody Map cond){
        Product pt = (Product)ResultUtil.transObject(cond, Product.class);
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(pt.getProductType())){
            wrapper.eq(Product::getProductType,pt.getProductType());
        }
        if(!StringUtils.isEmpty(pt.getProName())){
            wrapper.like(Product::getProName,pt.getProName());
        }
        if(!StringUtils.isEmpty(pt.getSellerNo())){
            wrapper.eq(Product::getSellerNo,pt.getSellerNo());
        }
        if(!StringUtils.isEmpty(pt.getStatus())){
            wrapper.eq(Product::getStatus,pt.getStatus());
        }
        Map<String,Object> result = new HashMap();
        IPage page = ParamUtils.getPage(cond);
        page = productService.pageMaps(page,wrapper);
        List<Map<String, Object>> datas = page.getRecords();
        List<Map<String,Object>> datas1 = new ArrayList<>();
        datas.forEach(map ->{
            Map<String,Object> tmap = new HashMap<>();
            tmap.putAll(map);
            Object obj = map.get("productType");
            if(obj != null){
                Long productType = (Long)obj;
                ProductType byId = productTypeService.getById(productType);
                tmap.put("productType",byId.getTypeName());
                tmap.put("productType_ori",productType);
            }
            datas1.add(tmap);
        }) ;
        ResultUtil.transfort(datas1,this.getDictMap(),true);
        result.put("total",page.getTotal());
        result.put("datas",datas1);
        return  Result.success(result);
    }


    /**
     * 获取列和字典值的映射关系
     * @return
     */
    private Map getDictMap(){
        Map<String,String> dictMap = new HashMap<>();
        dictMap.put("status","productStatus");
        return dictMap;
    }

}
